﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;

namespace MachineBuildingSystem
{
    class CommonHelper
    {
        public static bool JsonLogin(string user, string password, ref string name)
        {
            //JsonUrl地址
            CGlobal.strJsonUrl = ConfigurationManager.AppSettings["JsonUrl"].ToString();
            CGlobal.strCur_user = user;
            CGlobal.strPasswd = password;
            //登录
            LoginCheckData bd = new LoginCheckData();
            bd.username = CGlobal.strCur_user;
            bd.password = CGlobal.strPasswd;
            CGlobal.strSwapJsonData = JsonConvert.SerializeObject(bd);
            string strRtnErrorMsg = string.Empty;
            name = "";
            int res = putLoginJsonData("Login", "", ref name, ref strRtnErrorMsg);
            if (res != -1)
            {
                LogHelper.error("Json登录失败：" + strRtnErrorMsg);
                throw new Exception("Json登录失败：" + strRtnErrorMsg);
            }
            return true;
        }

        //发送json数据
        public static int putLoginJsonData(string WorkFlowType, string flowno, ref string name,  ref string strErrorMsg)
        {
            if (!CGlobal.Connected_To_Network())
            {
                strErrorMsg = "网络未连接!";
                return -2;
            }
            try
            {
                string url = "";
                url = getURL(WorkFlowType, flowno);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Timeout = 180000;
                if (CGlobal.cookie != null)
                    request.Headers.Add("Cookie", CGlobal.cookie);
                request.ContentType = "application/json;charset=UTF-8";
                //request.ContentType = "text/xml";

                request.Accept = "application/json";
                request.Method = "PUT";
                request.AllowWriteStreamBuffering = true;

                byte[] postBytes = Encoding.UTF8.GetBytes(CGlobal.strSwapJsonData);
                request.ContentLength = postBytes.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postBytes, 0, postBytes.Length);
                requestStream.Flush();
                requestStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();


                bool exception = true;
                if (response.Headers["Set-Cookie"] != null)
                    CGlobal.cookie = response.Headers.Get("Set-Cookie");
                if (response.Headers["Date"] != null)
                    CGlobal.dtLoginTime = Convert.ToDateTime(response.Headers.Get("Date"));
                if (response.Headers["Exception"] != null)
                    exception = Convert.ToBoolean(response.Headers.Get("Exception"));

                Stream responseStream = response.GetResponseStream();
                string stringResponse = string.Empty;
                //UTF8方式读取上传返回信息字符串
                using (StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8))
                {
                    stringResponse = responseReader.ReadToEnd();
                }

                responseStream.Close();
                response.Close();

                if (exception)
                {
                    //异常
                    responseResult result = JsonConvert.DeserializeObject<responseResult>(stringResponse);
                    strErrorMsg = result.message;
                    return result.type;
                }
                else
                {
                    JObject jo = (JObject)JsonConvert.DeserializeObject(stringResponse);
                    name = jo["name"].ToString();

                    if (stringResponse == "[]")
                    {
                        //提交成功
                        strErrorMsg = "";
                        return -1;
                    }
                    else
                    {
                        {
                            //提交成功，但有部分数据在服务器端失败被返回，登录除外
                            strErrorMsg = stringResponse;
                            return -1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //网络或系统异常
                strErrorMsg = ex.Message;
                return -3;
            }
            finally
            {
                //无论成功与否，都清空。有的jsondata很长
                CGlobal.strSwapJsonData = string.Empty;
            }
        }
        //发送json数据
        public static int putJsonData(string WorkFlowType, string flowno, ref string strErrorMsg)
        {
            if (!CGlobal.Connected_To_Network())
            {
                strErrorMsg = "网络未连接!";
                return -2;
            }
            try
            {
                string url = "";
                url = getURL(WorkFlowType, flowno);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Timeout = 180000;
                if (CGlobal.cookie != null)
                    request.Headers.Add("Cookie", CGlobal.cookie);
                request.ContentType = "application/json;charset=UTF-8";
                //request.ContentType = "text/xml";

                request.Accept = "application/json";
                request.Method = "PUT";
                request.AllowWriteStreamBuffering = true;

                byte[] postBytes = Encoding.UTF8.GetBytes(CGlobal.strSwapJsonData);
                request.ContentLength = postBytes.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postBytes, 0, postBytes.Length);
                requestStream.Flush();
                requestStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();


                bool exception = true;
                if (response.Headers["Set-Cookie"] != null)
                    CGlobal.cookie = response.Headers.Get("Set-Cookie");
                if (response.Headers["Date"] != null)
                    CGlobal.dtLoginTime = Convert.ToDateTime(response.Headers.Get("Date"));
                if (response.Headers["Exception"] != null)
                    exception = Convert.ToBoolean(response.Headers.Get("Exception"));

                Stream responseStream = response.GetResponseStream();
                string stringResponse = string.Empty;
                //UTF8方式读取上传返回信息字符串
                using (StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8))
                {
                    stringResponse = responseReader.ReadToEnd();
                }

                responseStream.Close();
                response.Close();

                if (exception)
                {
                    //异常
                    responseResult result = JsonConvert.DeserializeObject<responseResult>(stringResponse);
                    strErrorMsg = result.message;
                    return result.type;
                }
                else
                {
                    if (stringResponse == "[]")
                    {
                        //提交成功
                        strErrorMsg = "";
                        return -1;
                    }
                    else
                    {
                        {
                            //提交成功，但有部分数据在服务器端失败被返回，登录除外
                            strErrorMsg = stringResponse;
                            return -1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //网络或系统异常
                strErrorMsg = ex.Message;
                return -3;
            }
            finally
            {
                //无论成功与否，都清空。有的jsondata很长
                CGlobal.strSwapJsonData = string.Empty;
            }
        }

        //获取json数据
        public static int getJsonData(string WorkFlowType, string flowno, ref string strErrorMsg)
        {
            int res = -1;

            if (!CGlobal.Connected_To_Network())
            {
                strErrorMsg = "网络未连接!";
                return -2;
            }

            string url = "";
            try
            {
                url = getURL(WorkFlowType, flowno);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                if (CGlobal.cookie != null)
                    request.Headers.Add("Cookie", CGlobal.cookie);

                request.ContentType = "application/json;charset=UTF-8";
                request.Accept = "application/json";
                request.Method = "GET";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                bool exception = true;
                if (response.Headers["Exception"] != null)
                    exception = Convert.ToBoolean(response.Headers.Get("Exception"));

                Stream stream = response.GetResponseStream();
                string jsondata = "";
                using (StreamReader reader = new StreamReader(stream))
                {
                    while (!reader.EndOfStream)
                    {
                        jsondata += reader.ReadLine();
                    }
                }
                stream.Close();
                response.Close();

                if (exception)
                {
                    //异常
                    responseResult result = JsonConvert.DeserializeObject<responseResult>(jsondata);
                    strErrorMsg = result.message;
                    return result.type;
                }
                //操作成功
                CGlobal.strSwapJsonData = jsondata;
                return res;
            }

            catch (WebException)  //webExcp
            {
                strErrorMsg = "服务器请求数据错误，请检查服务器是否运行。" + CGlobal.strJsonUrl;
                return 1;
            }

            catch (Exception ex)
            {
                //网络或系统异常
                strErrorMsg = ex.Message;
                return 1;
            }
        }
        
        //同步数据时获取json数据
        public static int getSyncJsonData(string WorkFlowType, string flowno, ref string strErrorMsg)
        {
            int res = -1;

            if (!CGlobal.Connected_To_Network())
            {
                strErrorMsg = "网络未连接!";
                return -2;
            }

            string url = "";
            try
            {
                url = getURL(WorkFlowType, flowno);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                if (CGlobal.cookie != null)
                    request.Headers.Add("Cookie", CGlobal.cookie);

                request.ContentType = "application/json;charset=UTF-8";
                request.Accept = "application/json";
                request.Method = "GET";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();


                Stream stream = response.GetResponseStream();
                string jsondata = "";
                using (StreamReader reader = new StreamReader(stream))
                {
                    while (!reader.EndOfStream)
                    {
                        jsondata += reader.ReadLine();
                    }
                }
                stream.Close();
                response.Close();

                //操作成功
                CGlobal.strSwapJsonData = jsondata;
                return res;
            }

            catch (WebException)  //webExcp
            {
                strErrorMsg = "服务器请求数据错误，请检查服务器是否运行。" + CGlobal.strJsonUrl;
                return 1;
            }

            catch (Exception ex)
            {
                //网络或系统异常
                strErrorMsg = ex.Message;
                return 1;
            }
        }

        public static int putSyncJsonData(string WorkFlowType, string flowno, ref string strErrorMsg)
        {
            if (!CGlobal.Connected_To_Network())
            {
                strErrorMsg = "网络未连接!";
                return -2;
            }
            try
            {
                //string serviceAddress = "http://192.168.1.5:90/igr/syncResult?systemId=subSystem001";
                //HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(serviceAddress);

                //request1.Method = "POST";
                //request1.ContentType = "application/json;charset=UTF-8";
                //string strContent = @"[{type:'user',id:'1', syncType:'0'. syncResult:'ok',cause:''}]";
                //using (StreamWriter dataStream = new StreamWriter(request1.GetRequestStream()))
                //{
                //    dataStream.Write(strContent);
                //    dataStream.Close();
                //}
                //HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse();

                //StreamReader reader = new StreamReader(response1.GetResponseStream(), Encoding.GetEncoding(encoding));





                string url = "";
                url = getURL(WorkFlowType, flowno);
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Timeout = 180000;
                if (CGlobal.cookie != null)
                    request.Headers.Add("Cookie", CGlobal.cookie);
                request.ContentType = "application/json;charset=UTF-8";
                request.Method = "POST";
                request.AllowWriteStreamBuffering = true;

                byte[] postBytes = Encoding.UTF8.GetBytes(CGlobal.strSwapJsonData);
                request.ContentLength = postBytes.Length;

                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postBytes, 0, postBytes.Length);
                requestStream.Flush();
                requestStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();


                Stream responseStream = response.GetResponseStream();
                string stringResponse = string.Empty;
                //UTF8方式读取上传返回信息字符串
                using (StreamReader responseReader = new StreamReader(responseStream, Encoding.UTF8))
                {
                    stringResponse = responseReader.ReadToEnd();
                }

                responseStream.Close();
                response.Close();

                JObject jo = (JObject)JsonConvert.DeserializeObject(stringResponse);
                string status = jo["status"].ToString();
                if (status != "ok")
                {
                    //异常
                    responseResult result = JsonConvert.DeserializeObject<responseResult>(stringResponse);
                    strErrorMsg = result.message;
                    return result.type;
                }
                else
                {
                    if (stringResponse == "[]")
                    {
                        //提交成功
                        strErrorMsg = "";
                        return -1;
                    }
                    else
                    {
                        {
                            //提交成功，但有部分数据在服务器端失败被返回，登录除外
                            strErrorMsg = stringResponse;
                            return -1;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //网络或系统异常
                strErrorMsg = ex.Message;
                return -3;
            }
            finally
            {
                //无论成功与否，都清空。有的jsondata很长
                CGlobal.strSwapJsonData = string.Empty;
            }
        }
        public static string getURL(string WorkFlowType, string flowno)
        {
            string url = "";
            url = CGlobal.strJsonUrl;
            switch (WorkFlowType)
            {
                case "Login":    //
                    url = url + "login";
                    break;
                case "saleOrders":    //订单
                    url = url + "saleOrders/" + flowno;
                    break;
                case "saleOrderSizes":    //订单数量
                    url = url + "saleOrderSizes/" + flowno;
                    break;
                case "customerlists":    //客户
                    url = url + "customerlists/" + flowno;
                    break;
                case "saleFormulas":    //实施配比
                    url = url + "saleFormulas/" + flowno;
                    break;
                case "materials":    //配方代码
                    url = url + "materials";
                    break;
                case "projectName":    //工程名
                    url = url + "projectName/" + flowno;
                    break;
                case "slump":    //坍落度
                    url = url + "slump/" + flowno;
                    break;
                case "areas":    //区域
                    url = url + "areas/" + flowno;
                    break;
                case "projectPosition":    //施工部位
                    url = url + "projectPosition";
                    break;
                case "transport":    //传送方式
                    url = url + "transport";
                    break;
                case "getSaleFormulasByStatus":    //根据状态获取实施配方
                    url = url + "getSaleFormulasByStatus/" + flowno;
                    break;
                case "saveSaleOrder":    //保存销售订单
                    url = url + "saveSaleOrder";
                    break;
                case "audited":    //审核订单
                    url = url + "audited/" + flowno;
                    break;
                case "updateExecuteStatus":    //更新订单状态
                    url = url + "updateExecuteStatus/" + flowno;
                    break;
                case "updateFormulaExecuteStatus":    //更新实施配比状态
                    url = url + "updateFormulaExecuteStatus/" + flowno;
                    break;
                case "saveReturnSale":    //退砼保存
                    url = url + "saveReturnSale/" + flowno;
                    break;
                case "saveBackSale":    // 发货单红冲
                    url = url + "saveBackSale/" + flowno;
                    break;
                case "saleDeliverys":    // 发货明细
                    url = url + "saleDeliverys/" + flowno;
                    break;
                case "saveSaleDelivery":    // 发货单保存
                    url = url + "saveSaleDelivery";
                    break;
                case "delSaleLine":    // 删除订单
                    url = url + "delSaleLine/" + flowno;
                    break;
                case "cusBalances":    // 关联客户销售金额
                    url = url + "cusBalances/" + flowno;
                    break;
                case "expenseType":    // 费用类别
                    url = url + "expenseType";
                    break;
                case "saleExpense":    // 查询销售费用
                    url = url + "saleExpense/" + flowno;
                    break;
                case "getSaleOutsByOrder":    // 查询出库清单
                    url = url + "getSaleOutsByOrder/" + flowno;
                    break;
                case "getSaleExpenseByOutLineId":    //  根据销售出库单子表来查询销售费用 (单车费用)
                    url = url + "getSaleExpenseByOutLineId/" + flowno;
                    break;
                case "getSaleExpenseAll":    // 根据销售定单子表来查询销售费用 (全部费用)
                    url = url + "getSaleExpenseAll/" + flowno;
                    break;
                case "getSaleExpenseBySaleLineId":    // 根据销售定单子表来查询销售费用 (整单费用)
                    url = url + "getSaleExpenseBySaleLineId/" + flowno;
                    break;
                case "saveSaleExpenses":    // 保存费用登记信息
                    url = url + "saveSaleExpenses";
                    break;
                case "deleteSaleExpense":    // 费用删除
                    url = url + "deleteSaleExpense/" + flowno;
                    break;
                case "dealSaleExpense":    // 费用审核
                    url = url + "dealSaleExpense";
                    break;
                case "orderPrice":    // 产品价格
                    url = url + "orderPrice/" + flowno;
                    break;
                case "getSaleFormulas":    // 根据销售订单得到实施配方orderId
                    url = url + "getSaleFormulas/" + flowno;
                    break;
                case "getSaConcreteFormulaLines":    // 根据实施配方主表得到实施配方子表信息id
                    url = url + "getSaConcreteFormulaLines/" + flowno;
                    break;
                case "sync"://同步基础数据
                    url = url.Split(new string[] { "mt" }, StringSplitOptions.RemoveEmptyEntries)[0] + "igr/sync?systemId=subSystem001&type=user";
                    break;
                case "syncResult"://同步数据返回结果
                    url = url.Split(new string[] { "mt" }, StringSplitOptions.RemoveEmptyEntries)[0] + "igr/syncResult?systemId=subSystem001";
                    break;
                case "getDateTime":    // 获取服务器时间
                    url = url + "getDateTime";
                    break;
                case "productInStoreSave":    // 入库保存
                    url = url + "productInStoreSave";
                    break;
                case "productOutStoreSave":    // 出库保存
                    url = url + "productOutStoreSave";
                    break;
                case "changeDelivery":    // 发货单修改车牌号司机
                    url = url + "changeDelivery";
                    break;
                default:
                    break;
            }
            return url;
        }

        public static DataInfo CreateDataInfo(long id, string value)
        {
            DataInfo data = new DataInfo();
            data.Id = id;
            data.Value = value;
            return data;
        }

        //根据编码获取DataInfo
        public static DataInfo FindDataInfoByKey(ComboBoxEdit cmb, long key)
        {
            foreach (DataInfo info in cmb.Properties.Items)
            {
                if (info.Id == key)
                {
                    return info;
                }
            }
            return null;
        }

        public static DataColumn CreateDataColumn(string columnName, string caption)
        {
            DataColumn column = new DataColumn();
            column.Caption = caption;
            column.ColumnName = columnName;
            return column;
        }

        /// <summary>
        /// 进行DES加密。
        /// </summary>
        /// <param name="pToEncrypt">要加密的字符串。</param>
        /// <param name="sKey">密钥，且必须为8位。</param>
        /// <returns>以Base64格式返回的加密字符串。</returns>
        public static string Encrypt(string pToEncrypt, string sKey)
        {
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Convert.ToBase64String(ms.ToArray());
                ms.Close();
                return str;
            }
        }

        /// <summary>
        /// 进行DES解密。
        /// </summary>
        /// <param name="pToDecrypt">要解密的以Base64</param>
        /// <param name="sKey">密钥，且必须为8位。</param>
        /// <returns>已解密的字符串。</returns>
        public static string Decrypt(string pToDecrypt, string sKey)
        {
            byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }

        public static void DrawCheckBox(DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e, bool chk)
        {
            RepositoryItemCheckEdit repositoryCheck = e.Column.ColumnEdit as RepositoryItemCheckEdit;
            if (repositoryCheck != null)
            {
                Graphics g = e.Graphics;
                Rectangle r = e.Bounds;

                DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo info;
                DevExpress.XtraEditors.Drawing.CheckEditPainter painter;
                DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs args;
                info = repositoryCheck.CreateViewInfo() as DevExpress.XtraEditors.ViewInfo.CheckEditViewInfo;

                painter = repositoryCheck.CreatePainter() as DevExpress.XtraEditors.Drawing.CheckEditPainter;
                info.EditValue = chk;
                info.Bounds = r;
                info.CalcViewInfo(g);
                args = new DevExpress.XtraEditors.Drawing.ControlGraphicsInfoArgs(info, new DevExpress.Utils.Drawing.GraphicsCache(g), r);
                painter.Draw(args);
                args.Cache.Dispose();
            }
        }

        public static bool ClickGridCheckBox(DevExpress.XtraGrid.Views.Grid.GridView gridView, string fieldName, bool currentStatus)
        {
            bool result = false;
            if (gridView != null)
            {
                gridView.ClearSorting();//禁止排序

                gridView.PostEditor();
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info;
                Point pt = gridView.GridControl.PointToClient(Control.MousePosition);
                info = gridView.CalcHitInfo(pt);
                if (info.InColumn && info.Column != null && info.Column.FieldName == fieldName)
                {
                    for (int i = 0; i < gridView.RowCount; i++)
                    {
                        gridView.SetRowCellValue(i, fieldName, !currentStatus);
                    }
                    return true;
                }
            }
            return result;
        } 
    }

    public class LoginCheckData
    {
        public string username { get; set; }
        public string password { get; set; }
    }

    public class responseResult
    {
        public int type { get; set; }
        public string message { get; set; }
    }

    public class CGlobal
    {
        public static string strSys_name;
        public static int nSafelock_time;  //minitue
        public static string strCur_user;
        public static string strPasswd;
        public static string strCur_deptid;
        public static string strCur_deptname;
        public static int keepPassword;
        public static DateTime dtLoginTime;
        public static string strJsonUrl;
        public static string strSwapJsonData = "";//Get/Put不同业务模块的JsonData中转，每次用完清空。
        public static string cookie = null;
        public static DateTime logindate = DateTime.Today;  //用来填入单据的日期

        public static Boolean bDebug = true;   //debug状态标志，json上下传和debug msg到debug.log。

        public static bool IsNumeric(string value)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(value, @"^[+-]?/d*[.]?/d*$");
        }
        public static bool IsInt(string value)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(value, @"^[+-]?/d*$");
        }
        public static bool IsUnsign(string value)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(value, @"^/d*[.]?/d*$");
        }

        /// <summary>
        ///if(CGlobal.bDebug)
        ///JSON IO debug信息都输出到@"\Application\wrWMSLog.txt
        /// </summary>
        /// <param name="strModule"></param>
        /// <param name="strType"></param>
        /// <param name="strLogMsg"></param>
        /// <returns></returns>
        public static bool PutDebugLog(string strModule, string strType, string strLogMsg)
        {
            string strDebugMsg = "";
            if (!CGlobal.bDebug)
                return true;
            else
                try
                {
                    FileStream aFile = new FileStream(@"\Application\Log.txt", FileMode.Append, FileAccess.Write);
                    StreamWriter sw = new StreamWriter(aFile, System.Text.Encoding.GetEncoding("gb2312"));
                    strDebugMsg = DateTime.Now.ToString() + ":" + CGlobal.strCur_user + ";" + strModule + ";" + strType + ";" + strLogMsg;

                    sw.WriteLine(strDebugMsg);
                    sw.Close();
                    return true;
                }
                catch
                {
                    return false;
                }
        }

        public static bool DelDebugLog()
        {
            try
            {
                if (File.Exists(@"\Application\Log.txt"))
                {
                    File.Delete(@"\Application\Log.txt");
                    return true;
                }
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        static public bool Connected_To_Network()
        {
            IPEndPoint localEndPoint = new IPEndPoint(Dns.Resolve(Dns.GetHostName()).AddressList[0], 0);
            try
            {
                if (localEndPoint.Address.ToString() == "127.0.0.1")
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        public static string varifyBarcode(string barcode, string header)
        {
            string ret = "";
            try
            {
                int i = barcode.Split((char)10).Length;
                if (i < 1 || barcode.Split((char)10)[0] != "WL")
                {
                    ret = "无效条码";
                    return ret;
                }
            }
            catch
            {
                ret = "条码解析错误";
                return ret;
            }
            return ret;
        }

        /// <summary>
        /// 
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        struct SYSTEMTIME
        {
            public ushort wYear;
            public ushort wMonth;
            public ushort wDayOfWeek;
            public ushort wDay;
            public ushort wHour;
            public ushort wMinute;
            public ushort wSecond;
            public ushort wMilliseconds;
        }

        [DllImport("coredll.dll")]
        private static extern bool SetLocalTime(ref SYSTEMTIME lpSystemTime);
        [DllImport("coredll.dll")]
        private static extern bool GetLocalTime(ref SYSTEMTIME lpSystemTime);

        public static void SetSysTime(DateTime date)
        {
            SYSTEMTIME lpTime = new SYSTEMTIME();
            lpTime.wYear = Convert.ToUInt16(date.Year);
            lpTime.wMonth = Convert.ToUInt16(date.Month);
            lpTime.wDay = Convert.ToUInt16(date.Day);
            lpTime.wHour = Convert.ToUInt16(date.Hour);
            lpTime.wMinute = Convert.ToUInt16(date.Minute);
            lpTime.wSecond = Convert.ToUInt16(date.Second);
            SetLocalTime(ref lpTime);
        }
    }

    //订单信息
    public class OrderInfo
    {
        public long mainId = 0;
        public long id = 0;
        //是否有新的实施配比
        public bool isHaveNewFormula = false;
        //厂商
        public long corpId = 0;
        //厂商
        public string corpName = "";
        // 订单编码
        public string orderCode = "";
        //订单日期
        public DateTime orderDate = DateTime.Now;
        //客户
        public long customerId = 0;
        public string customerCode = "";
        public string customerName = "";
        //配方代码
        public long materialId = 0;
        public string materialCode = "";
        public string materialName = "";
        //强度等级根据物料的规格型号
        public string materialSstd = "";
        //物料坍落度
        public string materialSlump = "";
        //强度等级
        public string strengthGrade = "";
        //订单数量
        public decimal orderQuantity = 0;
        //发货数量
        public decimal sendQuantity = 0;
        //工程名称
        public string projectName = "";
        //预定生产时间
        public DateTime productDate = DateTime.Now;
        //施工部位
        public string constructSite = "";
        //坍落度
        public string slump = "";
        //其他技术要求
        public string otherRequirement = "";
        //输送方式
        public string transport = "";
        //输送方式类型
        public long types = -1;
        //基本计价路程
        public decimal basicPath = 0;
        //基本运价
        public decimal basicPrice = 0;
        //超公里路程
        public decimal superPath = 0;
        //超公里运价
        public decimal superPrice = 0;
        //单价
        public decimal unitPrice = 0;
        //委托人电话
        public string phone = "";
        //区域
        public string areaName = "";
        //区域调价
        public decimal areaPrice = 0;
        //生产线Id
        public long workingId = -1;
        //生产线名称
        public string workingCenterName = "";
        //实际距离
        public decimal actualRange = 0;
        //产品价格
        public decimal productPrice = 0;
        //混凝土货款
        public decimal concreteLoan = 0;
        //订单状态
        public int executeStatus = 0;
        //审核状态
        public bool audited = false;
        //版本号
        public long version = 0;

        //施工地址
        public string constructionAddr = "";
        //助记码
        public string otherCode = "";
    }

    //发货明细
    public class DeliveryInfo
    {
        public long id = 0;
        //发货日期
        public DateTime deliDate = DateTime.Now;
        //发货编码
        public string deliCode = "";
        //客户
        public long customerId = 0;
        public string customerCode = "";
        public string customerName = "";
        //配方代码
        public long materialId = 0;
        public string materialCode = "";
        public string materialName = "";
        public string materialSstd = "";
        //发货数量
        public decimal deliQuantity = 0;
        public decimal outQuantity = 0;
        //回收数量
        public decimal recoveredQuantity = 0;
        //生产数量
        public decimal productQuantity = 0;
        //生产线名称
        public string workingCenterName = "";
        //车牌号
        public string carCode = "";
        //司机
        public string driverName = "";
        //发货人
        public string makerName = "";
        //退砼状态0 全部签收，废料处理, 1 全部签收，直接发往本客户其他工地, 2 全部签收，调料后发往其他工地 ,
        //3 部分签收，废料处理, 4部分签收，直接发往本客户其他工地理 ,5 部分签收，调料后发往其他工地
        //6调拨发货，发往本客户其他工地 7剩余发货，发往其他工地8部分退货
        public int returnStatus = -1;
        //退砼数量
        public decimal returnQuantity = 0;
        //备注
        public string remarks = "";
        //是否作废
        public bool invalid = false;
    }

    public enum ReturnStatusEnum : int
    {
        //"全部签收，废料处理"
        ALLSIGNS_WASTE = 0,
        //"全部签收，直接发往本客户其他工地"
        ALLSIGNS_SELF = 1,
        //"全部签收，调料后发往其他工地"
        ALLSIGNS_OTHER = 2,
        //"部分签收，废料处理"
        PARTSIGNS_WASTE = 3,
        //"部分签收，直接发往本客户其他工地"
        PARTSIGNS_SELF = 4,
        //"部分签收，调料后发往其他工地"
        PARTSIGNS_OTHER = 5,
        //调拨发货，发往本客户其他工地
        ALLOCATE_SELF = 6,
        //剩余发货，发往其他工地
        RETURN_OTHER = 7,
        //部分退货
        PART_BACK = 8
    }
    	

    //实施配方信息
    public class FormulasInfo
    {
        public long id = 0;
        //等级
        public decimal grade = 0;
        //标号
        public decimal labels = 0;
        //水泥物料
        public string cementMaterialCode = "";
        public string cementMaterialName = "";
        public string cementMaterialSstd = "";
        public decimal cementQuantity = 0;
        //矿粉物料
        public string mineMaterialCode = "";
        public string mineMaterialName = "";
        public string mineMaterialSstd = "";
        public decimal mineQuantity = 0;
        //煤灰物料
        public string coalMaterialCode = "";
        public string coalMaterialName = "";
        public string coalMaterialSstd = "";
        public decimal coalQuantity = 0;
        //砂1物料
        public string snadMaterial1Code = "";
        public string snadMaterial1Name = "";
        public string snadMaterial1Sstd = "";
        public decimal sandQuantity1 = 0;
        //砂2物料
        public string snadMaterial2Code = "";
        public string snadMaterial2Name = "";
        public string snadMaterial2Sstd = "";
        public decimal sandQuantity2 = 0;
        //石1物料
        public string stoneMaterial1Code = "";
        public string stoneMaterial1Name = "";
        public string stoneMaterial1Sstd = "";
        public decimal stoneQuantity1 = 0;
        //石2物料
        public string stoneMaterial2Code = "";
        public string stoneMaterial2Name = "";
        public string stoneMaterial2Sstd = "";
        public decimal stoneQuantity2 = 0;
        //外加剂物料
        public string admixtureMaterialCode = "";
        public string admixtureMaterialName = "";
        public string admixtureMaterialSstd = "";
        public decimal admixtureQuantity = 0;
        //水
        public decimal water = 0;
        //实施日期
        public DateTime formulaDate = DateTime.Now;
        //是否执行
        public bool isExecute = false;
        //执行时间
        public DateTime executeDate = DateTime.Now;
    }

    //客户信息
    public class CustomerInfo
    {
        public long customerId = 0;
        public string customerCode = "";
        public string customerName = "";
    }

    //工程信息
    public class ProjectInfo
    {
        //工程名称
        public string name = "";
        //实际距离
        public string range = "";
        //区域信息（工程名称带出区域）
        public ZoneInfo zoneInfo = new ZoneInfo();
    }

    //坍落度信息
    public class SlumpInfo
    {
        //id
        public long id = -1;
        //名称
        public string name = "";
    }

    //区域信息
    public class ZoneInfo
    {
        public long id = -1;
        //名称
        public string names = "";
        //基本价格
        public decimal basicPrice = 0;
        //区域单价
        public decimal price = 0;
        //超公里运价
        public decimal overPrice = 0;
        //补方价格
        public decimal supplyPrice = 0;
        //基本计价路程
        public decimal basicDistance = 0;
        //所属公司
        public string belongCorp = "";
    }

    //传送方式
    public class TransportInfo
    {
        public long id = 0;
        public string names = "";
        public long types = -1;
    }

    //施工部位
    public class ConstructSiteInfo
    {
        public long id = 0;
        public string names = "";
    }

    // 实施配方执行状态信息
    public class FormulasStatusInfo
    {
        //实施配比Id
        public long id = 0;
        //订单Id
        public long saleId = 0;
        //订单编码
        public string orderCode = "";
        //实施日期
        public DateTime formulaDate = DateTime.Now;
        //执行日期
        public DateTime executeDate = DateTime.Now;
        //执行状态
        public bool executeStatus = false;
    }


    //物料信息
    public class MaterialInfo
    {
        public long materialId = 0;
        public string materialCode = "";
        public string materialName = "";
        public string materialSstd = "";
    }

    //实施配比执行状态事件信息
    public class FormulasStatusEventArgs : EventArgs
    {
        private long m_OrderId = -1;
        public long OrderId
        {
            get { return m_OrderId; }
        }

        public FormulasStatusEventArgs(long orderId)
        {
            m_OrderId = orderId;
        }
    }

    public class DataInfo
    {
        public long Id { get; set; }
        public string Value { get; set; }
        public override string ToString()
        {
            return Value;
        }
    }

    public class DataStrInfo
    {
        public string Key { get; set; }
        public string Value { get; set; }
        public override string ToString()
        {
            return Value;
        }
    }
    public class OrderArgument : EventArgs
    {
        private OrderTypeEnum m_Type = new OrderTypeEnum();
        private OrderInfo m_OrderInfo;
        public OrderArgument(OrderTypeEnum type, OrderInfo orderInfo)
        {
            m_Type = type;
            m_OrderInfo = orderInfo;
        }

        public OrderTypeEnum Type
        {
            get { return m_Type; }
        }
        public OrderInfo OrderInfo
        {
            get { return m_OrderInfo; }
        }
    }

    //初始化时基础数据结构
    public class BaseDataInfo
    {
        public List<CustomerInfo> CustomerInfoList = new List<CustomerInfo>();
        public List<MaterialInfo> MaterialInfoList = new List<MaterialInfo>();
        public List<ProjectInfo> ProjectInfoList = new List<ProjectInfo>();
        public List<SlumpInfo> SlumpInfoInfoList = new List<SlumpInfo>();
        public List<ZoneInfo> ZoneInfoList = new List<ZoneInfo>();
        public List<ConstructSiteInfo> ConstructSiteInfoList = new List<ConstructSiteInfo>();
        public List<TransportInfo> TransportInfoList = new List<TransportInfo>();
    }

    public enum ExecuteStatusEnum : int
    {
        //未执行
        UN_EXECUTE = 0,
        //执行
        EXECUTE = 1,
        //暂停
        PAUSE = 2,
        //关闭
        CLOSE = 3
    }

    //退砼信息
    public class BackConcreteInfo
    {
        //发货单Id
        public long DeliveryId = 0;
        //数量
        public decimal Number = 0;
        //说明
        public string Explain = "";
        //退砼状态
        public int State = 0;
        //订单Id
        public long OrderId = 0;
    }

    public enum OrderTypeEnum : int
    {
        //订单新增
        OrderAdd = 0,
        //订单详情
        OrderDetail = 1,
        //订单修改
        OrderUpdate = 2,
        //订单修改(订单已审核，只能修改预定生产时间和实际距离)
        OrderUpdateByAudited = 3,
        //发货新增
        DeliveryAdd = 4,
        //发货详情
        DeliveryDetail = 5
    }

    public class DeliverySaveData
    {
        public long Autoid { get; set; }
        public long orderId { get; set; }
        public string carCode { get; set; }
        public string driverName { get; set; }
        public long workingId { get; set; }
        public string workingName { get; set; }
        public decimal productQuantity { get; set; }
        public decimal recoveredQuantity { get; set; }
        public DateTime deliDate { get; set; }
    }

    //费用类别信息
    public class ExpenseTypeData
    {
        public long id = 0;
        //费用名称
        public string names = "";
        //费用类别
        public string types = "";
    }

    //费用信息
    public class SaleExpenseData
    {
        public long id = 0;
        //费用登记时间
        public DateTime expenseDate = DateTime.MinValue;
        //费用名称
        public string expenseName = "";
        //数量
        public decimal quantity = 0;
        //单价
        public decimal price = 0;
        //金额
        public decimal moneys = 0;
        //备注
        public string remarks = "";
        //审核状态
        public int status = 0;
        //审核人
        public string checker = "";
        //审核时间
        public DateTime checkDate = DateTime.MinValue;
        //司机
        public string driverName = "";
        //车牌号
        public string carCode = "";
        //发货时间
        public DateTime deliveryDate = DateTime.MinValue;
        //是否自动生成费用
        public bool isAuto = false;
        //是否作废
        public bool invalid = false;
        //制单人
        public string sheetMaker = "";
        //创建时间
        public DateTime createDate = DateTime.MinValue;
    }

    //出库信息
    public class SaleOutsData
    {
        //销售出库单子表id
        public long id = 0;
        //客户编码
        public string customerCode = "";
        //客户名称
        public string customerName = "";
        //出库日期
        public DateTime outDate = DateTime.MinValue;
        //出库数量
        public decimal outQuantity = 0;
        //订单子表的工程名称
        public string projectName = "";
        //施工部位
        public string constructSite = "";
        //坍落度要求
        public string slump = "";
        //区域名称
        public string areaName = "";
        // 单价
        public decimal unitPrice = 0;
        //金额
        public decimal money = 0;
        //预算金额
        public decimal finalMoney = 0;
        //预算单价
        public decimal finalPrice = 0;
        //发票 金额
        public decimal invoiceMoney = 0;
        //发票 金额
        public decimal invoicePrice = 0;
        //司机
        public string driverName = "";
        //车牌号
        public string carCode = "";
        //发货时间
        public DateTime deliveryDate = DateTime.MinValue;
    }

    public enum ExpenseTypeEnum : int
    {
        //全部费用
        ExpenseAll = 0,
        //单车费用
        ExpenseSingle = 1,
        //整单费用
        ExpenseEntire = 2,
        //货款
        Payment = 3
    }

    //实施配方主表信息
    public class SaleFormulasData
    {
        //主表ID
        public long id = 0;
        //标号
        public string labels = "";
        //实施日期
        public DateTime formulaDate = DateTime.MinValue;
        //执行日期
        public DateTime executeDate = DateTime.MinValue;
        //执行状态
        public string executeStatus = "";
        //助记码
        public string otherCode = "";
        //字表信息
        public List<SaConcreteFormulaData> SaConcreteFormulaDataList = new List<SaConcreteFormulaData> ();
    }

    //实施配方字表信息
    public class SaConcreteFormulaData
    {
        //字表ID
        public long id = 0;
        // 物料id
        public long materialId = 0;
        // 物料编码
        public string materialCode = "";
        // 物料名称
        public string materialName = "";
        // 规格型号
        public string materialSstd = "";
        // 用量
        public decimal quantity = 0;
        // 仓位名称
        public string controlStoreName = "";
    }

    //同步时用户信息
    public class UserData
    {
        //用户ID
        public long id = -1;
        //同步类型0-新增，1-更新, 2-删除
        public long type = 0;
        //用户名 
        public string username = "";
        //密码
        public string password = "";
        //职员姓名
        public long employeeId = 0;
        //职员中文名
        public string employeeName = "";
        //所在公司 
        public string corp = "";
        //部门ID
        public long deptId = -1;
    }


    //同步后返回同步结果
    public class SyncResult
    {
        //数据类型
        public string type = "user";
        //实体id
        public long id = 0;
        //同步类型:  0-新增，1-更新, 2-删除
        public long syncType = 0;
        //成功为ok，失败为failed
        public string syncResult = "";
        //失败原因 
        public string cause = "";
    }


    public enum ActionEnum : int
    {
        //权限分配
        Action = 0,
        //查询订单
        OrderSearch = 1,
        //创建订单
        OrderAdd = 2,
        //修改订单
        OrderUpdate = 3,
        //删除订单
        OrderDel = 4,
        //订单作废
        OrderPause = 5,
        //关闭订单
        OrderClose = 6,
        //订单审核
        OrderCheck = 7,
        //创建发货单
        DeliAdd = 8,
        //查询发货单
        DeliSearch = 9,
        //确认配比
        Formula = 10,
        //红冲
        Red = 11,
        //退砼
        BackConcrete = 12,
        //新增费用
        FeeAdd = 13,
        // 删除费用
        FeeDel = 14,
        // 费用审核
        FeeCheck = 15,
        // 费用弃核
        FeeUnCheck = 16,
        // 费用审核不通过
        FeeCheckUnPass = 17,
        //分页设置
        PageSet = 18,
        //发货单修改
        DeliModify = 19
    }

    public class ProductConsumeData
    {
        //生产订单i
        public string ProdNo = "";
        //批次号 (同一个订单有不同批次)
        public string Batchno = "";
        // 物料名称
        public string MaterialName = "";
        // 物料类型
        public string MaterialType = "";
        //理论值
        public decimal MAcademic = 0;
        //设定值
        public decimal MDesign = 0;
        //消耗值
        public decimal MAct = 0;
        //批次时间
        public DateTime BatchTime = DateTime.MinValue;
        //仓库号
        public int StoreNo = 0;
        //生产时间
        public DateTime Pdate = DateTime.MinValue;
        //生产线
        public string ProductLine = "";
        //配方值
        public decimal RecipeValue = 0;
        //调整值
        public decimal BatchAdd = 0;
    }

    //费用审核状态
    public enum ExpenseCheckEnum : int
    {
        //未审核
        NotAudited = 0,
        //已审核
        Audited = 1,
        //不通过
        NotPass = 2
    }

    //生产数据信息
    public class ProductDataInfo
    {
        //生产订单号
        public long Prodno = -1;
        //生产方量
        public decimal Volume = 0;
        //生产时间
        public DateTime pdate = DateTime.MinValue;
    }
}